package com.yeban.bams.server.log;

import javax.swing.*;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class LogManager {
    private static final List<LogEntry> logs = new ArrayList<>();
    private static final CopyOnWriteArrayList<Runnable> listeners = new CopyOnWriteArrayList<>();
    private static final DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    public static void addLog(String who, String action) {
        String time = LocalDateTime.now().format(fmt);
        synchronized (logs) { logs.add(new LogEntry(time, who, action)); }
        for (Runnable r : listeners) SwingUtilities.invokeLater(r);
    }

    public static List<LogEntry> getLogs() {
        synchronized (logs) { return Collections.unmodifiableList(new ArrayList<>(logs)); }
    }

    public static void addListener(Runnable r) { listeners.addIfAbsent(r); }
    public static void removeListener(Runnable r) { listeners.remove(r); }
}